import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BindPlayerE2PDto } from '../dto/bind-player-e2p.dto';
import { EventToPlayer } from '../entities/event-to-player.entity';
import logger from 'src/common/utils/log';
import { EventToPlayerService } from '../event-to-player.service';
import { PlayerSignupService } from 'src/modules/player-signup/service/player-signup.service';
import { PlayerSignup } from 'src/modules/player-signup/entities/player-signup.entity';
import { EventToPlayerCacheService } from '../event-to-player.cache.service';

@Injectable()
export class BindPlayerService {
  constructor(
    @InjectRepository(EventToPlayer)
    private readonly repository: Repository<EventToPlayer>,
    private readonly eventToPlayerService: EventToPlayerService,
    private readonly playerSignupService: PlayerSignupService,
    private readonly e2pCacheService: EventToPlayerCacheService,
  ) {}

  async bindPlayerToE2P(BindPlayerE2PDtos: Array<BindPlayerE2PDto>) {
    // 将报名人员绑定到E2P
    logger.info(`start bindPlayerToE2P`);
    const promiseList = [];
    BindPlayerE2PDtos.forEach((BindPlayerE2PDto) => {
      promiseList.push(this.getBindE2P(BindPlayerE2PDto));
    });
    const e2ps = await Promise.all(promiseList);
    const res = await this.repository.save(e2ps);
    console.log('res', res);
    await this.e2pCacheService.handleEventToPlayerUpdate(res);
    logger.info(`end bindPlayerToE2P ${e2ps.length}`);
    return res;
  }
  async getBindE2P(BindPlayerE2PDto: BindPlayerE2PDto): Promise<EventToPlayer> {
    // 获取要保存数据的E2P
    logger.info(`start getBindE2P`);
    const { id, playerId, player2Id, isByePlayer } = BindPlayerE2PDto;
    if (!id) {
      throw new HttpException(
        `参数不完整,id 不存在`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
    const e2p = await this.eventToPlayerService.findOne(id);
    if (!e2p) {
      throw new HttpException(
        `id:${id} e2p 不存在`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
    const updateOldSignups = [];
    const { player1Id: oldPlayer1Id, player2Id: oldPlayer2Id } = e2p;
    const oldPlayerIds = [];
    let oldPlayers = [];
    if (oldPlayer1Id) {
      oldPlayerIds.push(oldPlayer1Id);
    }
    if (oldPlayer2Id) {
      oldPlayerIds.push(oldPlayer2Id);
    }
    if (oldPlayerIds.length > 0) {
      oldPlayers = await this.playerSignupService.findByIds(oldPlayerIds);
      if (oldPlayers.length) {
        oldPlayers.forEach((player: PlayerSignup) => {
          player.isMainPlayer = false;
          updateOldSignups.push(player);
        });
      }
    }
    await this.playerSignupService.saveList(updateOldSignups);
    if (isByePlayer === true) {
      e2p.isByePlayer = isByePlayer;
      e2p.player1Id = null;
      e2p.player1Name = '轮空';
      e2p.player2Id = null;
      e2p.player2Name = null;
    } else {
      const playerIds = [];
      e2p.isByePlayer = false;
      if (playerId) {
        playerIds.push(playerId);
      }
      if (player2Id) {
        playerIds.push(player2Id);
      }
      if (!playerIds.length) {
        e2p.player1Id = null;
        e2p.player1Name = null;
        e2p.player2Id = null;
        e2p.player2Name = null;
      } else {
        const newSignups = [];
        const players = await this.playerSignupService.findByIdsAndEventId(
          playerIds,
          e2p.eventId,
        );
        if (players.length !== playerIds.length) {
          throw new HttpException(
            `需要绑定的玩家${playerIds.length},查到玩家${players.length},${playerIds.map((item) => item.id)}`,
            HttpStatus.INTERNAL_SERVER_ERROR,
          );
        }
        players.forEach((player: PlayerSignup) => {
          // player.isMainPlayer = true;
          const samePlayer = newSignups.find(
            (oldPlayer) => oldPlayer.id === player.id,
          );
          if (samePlayer) {
            samePlayer.isMainPlayer = true;
          } else {
            player.isMainPlayer = true;
            newSignups.push(player);
          }
        });
        const _player1 = players[0];
        e2p.player1Id = _player1.id;
        e2p.player1Name = _player1.name;

        const _player2 = players[1];
        e2p.player2Id = _player2?.id || null;
        e2p.player2Name = _player2?.name || null;
        logger.info(`newSignups ${newSignups.length}`);
        if (newSignups.length) {
          await this.playerSignupService.saveList(newSignups);
        }
      }
    }

    logger.info(`end getBindE2P`);
    return e2p;
  }
}
